package com.jerry.walking.module.activityPage.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jerry.walking.R;
import com.jerry.walking.base.BaseActivity;
import com.jerry.walking.base.BaseApplication;
import com.jerry.walking.constant.Urls;
import com.jerry.walking.module.activityPage.adapter.ImagePagerAdapter;
import com.jerry.walking.module.activityPage.bean.ActivityContent;
import com.jerry.walking.utils.Base64Util;
import com.jerry.walking.utils.CollectionUtils;
import com.jerry.walking.utils.DateUtils;
import com.jerry.walking.utils.EventMessage;
import com.jerry.walking.utils.OkHttpUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.greenrobot.event.EventBus;
import greendao.LoreDetailTable;
import greendao.LoreDetailTableDao;

/**
 * Created by Administrator on 2016/5/12 0012.
 */
public class TravelDetailActivity extends BaseActivity{

    //评论
    @BindView(R.id.iv_comment)
    ImageView ivComment;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content_title)
    TextView tvContentTitle;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_logo)
    TextView tvLogo;
    @BindView(R.id.tv_act_time)
    TextView tvActTime;
    @BindView(R.id.tv_act_days)
    TextView tvActDays;
    @BindView(R.id.tv_act_place)
    TextView tvActPlace;
    @BindView(R.id.tv_stay_way)
    TextView tvStayWay;
    @BindView(R.id.tv_act_price)
    TextView tvActPrice;
    @BindView(R.id.tv_gather_place)
    TextView tvGatherPlace;
    @BindView(R.id.tv_attraction)
    TextView tvAttraction;
    @BindView(R.id.tv_routes)
    TextView tvRoutes;
    @BindView(R.id.tv_equipment)
    TextView tvEquipment;
    @BindView(R.id.tv_cost_detail)
    TextView tvCostDetail;
    @BindView(R.id.tv_application_notes)
    TextView tvApplicationNotes;
    @BindView(R.id.sv_content)
    ScrollView svContent;
    @BindView(R.id.tv_act_cate)
    TextView tvActCate;
    @BindView(R.id.tb_bar)
    Toolbar tbBar;
    @BindView(R.id.vp_images)
    ViewPager vpImages;

    private ImagePagerAdapter pagerAdapter;
    private List<List<Integer>> list;
    private int categoryId;
    private String phone;
    private String logoTile;
    private String id;
    private LoreDetailTableDao dao;

    @Override
    protected int getLayoutId(){
        return R.layout.activity_travel_detail;
    }

    @Override
    protected void initViews(){

        dao = BaseApplication.getApplication().getDaoSession().getLoreDetailTableDao();



        ShareSDK.initSDK(this);
        Intent intent = getIntent();
        categoryId = intent.getIntExtra("categoryId", 0);
        tbBar.setTitle("");
        tbBar.inflateMenu(R.menu.base_toolbar_menu);
        list = new ArrayList<>();

        tbBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener(){
            @Override
            public boolean onMenuItemClick(MenuItem item){
                Toast.makeText(TravelDetailActivity.this, ""+"分享", Toast.LENGTH_SHORT).show();
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle("徒步去旅行");
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl("http://sharesdk.cn");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("我是分享文本，啦啦啦~");
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");
                // 启动分享GUI
                oks.show(TravelDetailActivity.this);
                return true;
            }
        });
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        ShareSDK.stopSDK(this);
    }

    //收藏
    @OnClick(R.id.bt_collect)
    void collect(){
        LoreDetailTable table = new LoreDetailTable();
        table.setId(Long.parseLong(id));
        table.setTitle(logoTile);
    }
    @OnClick(R.id.bt_sign)
    void sign(){
        
    }

    //拨号
    @OnClick(R.id.bt_dialog)
    void dialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflaterDl.inflate(R.layout.dialog_custom, null);
        final Dialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView textView = (TextView) layout.findViewById(R.id.tv_dialog_logo);
        textView.setText(logoTile);
        TextView textPhone = (TextView) layout.findViewById(R.id.tv_phone);
        textPhone.setText("("+phone+")");
        Button btConfirm  = (Button) layout.findViewById(R.id.bt_confirm);
        btConfirm.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                if(ActivityCompat.checkSelfPermission(TravelDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){

                }
                dialog.dismiss();
                startActivity(intent);
            }
        });
        Button btnCancel = (Button) layout.findViewById(R.id.bt_cancle);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

   

    @Override
    protected void loadData(){
        OkHttpUtils.get(Urls.ACTIVITY_DETAIL + categoryId, new OkHttpUtils.OnGetDataListener(){
            @Override
            public void onResponse(String url, String data){
                if(data != null){
                    EventBus.getDefault().post(new EventMessage(data, url));
                }
            }

            @Override
            public void onFailure(String url, String error){
            }
        });

    }

    @Override
    protected void postEventResult(@NonNull EventMessage message){
        if((Urls.ACTIVITY_DETAIL + categoryId).equals(message.type)){
            Gson gson = new Gson();
            ActivityContent activityContent = gson.fromJson(message.result, ActivityContent.class);
            initData(activityContent);
        }

    }


    //分享
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.ac_share:

                break;
            default:
                break;
        }
        //         Toast.makeText(MainActivity.this, ""+item.getItemId(), Toast.LENGTH_SHORT).show();

        return true;
    }

    private void initData(ActivityContent activityContent){
        pagerAdapter = new ImagePagerAdapter(this, list, activityContent);
        String title = Base64Util.decode(activityContent.getTitle());
        ImageLoader imageLoader = BaseApplication.getApplication().getImageLoader();
        DisplayImageOptions options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY).showImageOnLoading(R.mipmap.tubuqu_leader_xiaomi).showImageOnFail(R.mipmap.tubuqu_leader_xiaomi).showImageForEmptyUri(R.mipmap.ic_launcher).build();
        ActivityContent.ClubBean club = activityContent.getClub();
        //        activityContent
        imageLoader.displayImage(club.getLogo(), ivLogo, options);
        tvTitle.setText(title);
        tvContentTitle.setText(title);
        logoTile = club.getTitle();
        tvLogo.setText(logoTile);
        LinearLayout linearLayout = null;
        //加载小图
        List<ActivityContent.PicturesBean> pictures = activityContent.getPictures();
        GridView gridView = new GridView(this);
        //        for(int i = 0; i < activityContent.getPictures().size(); i++){
        //
        //            if(i%5 == 0){
        //                linearLayout = new LinearLayout(this);
        //            }
        //            list.add(linearLayout);
        //        }
        //        vpImages.setAdapter(pagerAdapter);
        //        pagerAdapter.notifyDataSetChanged();
        phone = club.getPhone();

        long start_time =((long)activityContent.getStart_time())*1000;

        Date date1 = new Date(start_time);
        String time = DateUtils.convertDateToString(date1);

        String period_desc = activityContent.getPeriod_desc();
        Log.d("time", "start_time=" + start_time);
        Log.d("time", "current_time=" + System.currentTimeMillis());

        //        recyclerView.setAdapter(adapter);
        // TODO: 2016/5/13 0013
        tvActTime.setText(TextUtils.isEmpty(period_desc) ? time : period_desc);
        tvActDays.setText(activityContent.getRoutes().size() + "天");
        tvActPlace.setText(Base64Util.decode(activityContent.getDestination()));
        vpImages.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();
        tvActCate.setText(CollectionUtils.join(activityContent.getTag()));
        tvStayWay.setText(Base64Util.decode(activityContent.getStay_place()));
        String min_cost = activityContent.getMin_cost();
        String max_cost = activityContent.getMax_cost();
        id = activityContent.getId();
        tvActPrice.setText("活动费用：" + (min_cost.equals(max_cost) ? (min_cost + "元/人") : (min_cost + "~" + max_cost + "元/人")));
        tvGatherPlace.setText("集合地点：" + Base64Util.decode(activityContent.getGather_place()));
        //活动亮点
        tvAttraction.setText(Base64Util.decode(activityContent.getAttraction()).replace("<br />", "\n"));
        //装备要求
        tvEquipment.setText(Base64Util.decode(activityContent.getEquipment()).replace("<br />", "\n"));
        //费用详情
        tvCostDetail.setText(Base64Util.decode(activityContent.getCost_detail()).replace("<br />", "\n"));
        //包名须知
        tvApplicationNotes.setText(Base64Util.decode(activityContent.getApplication_notes()).replace("<br />", "\n"));
        //详细行程
        List<ActivityContent.RoutesBean> routes = activityContent.getRoutes();
        List<String> routeDetail = new ArrayList<>();
        for(int i = 0; i < routes.size(); i++){
            routeDetail.add(Base64Util.decode(routes.get(i).getContent()));
            routeDetail.add("\n");
        }
        tvRoutes.setText(CollectionUtils.joinBlank(routeDetail));
    }

    @OnClick(R.id.imageView)
    void back(){
        finish();
    }

}
